import React, { Component } from 'react'
import Storage from './../storage.js'

var data = new Storage('data')

/* 高阶组件 High Order Component 例子 */
var StorageComponent = WrappedComponent => class extends Component {
  constructor(props) {
    super(props)
    this.state = {
      storage: data.get()
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleGet = this.handleGet.bind(this)
  }
  proc(wrappedComponentInstance) {
    wrappedComponentInstance.method()
  }
  handleGet() {
    return data.get()
  }
  handleChange() {
    var { count } = data.get()
    if (count !== null) {
      data.set({ count: count + 1})
    } else {
      data.set({ count: 0 })
    }
    console.log(data.get())
    this.setState({
      storage: data.get()
    })
  }
  render () {
    const newProps = {
      storage: {
        count: this.state.storage.count,
        onChange: this.handleChange
      }
    }
    return <WrappedComponent {...this.props} {...newProps} />
  }
}

export default StorageComponent

/**
 *【拓展】
 * React Router 2.4 新增 withRouter 这个 HoC
 * 这是除 context 外另一种获取 router 的推荐方式
 * https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.4.0.md
 *
 * 本项目中的 Redirect 组件用到了该高阶组件
 */
